package com.magictower.primary.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.telephony.PhoneStateListener;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;

import com.android.internal.telephony.ITelephony;

import java.lang.reflect.Method;

import com.magictower.primary.common.SPConstant;
import com.magictower.primary.db.dao.BlackNumberDao;

/**
 * @author kejunzhan
 * @since 2017/12/12
 */

public class CallSafeService extends Service {
    private BlackNumberDao dao;
    private TelephonyManager tm;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("onBind method");
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        SharedPreferences sp = getSharedPreferences(SPConstant.CONFIG, MODE_PRIVATE);
        boolean open = sp.getBoolean(SPConstant.BLACK_NAME, true);//默认开启黑名单
        if (!open) {
            return;
        }

        dao = new BlackNumberDao(this);
        //获取系统的电话服务
        tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        MyPhoneStateListener listener = new MyPhoneStateListener();
        tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);//监听电话状态的改变

        //初始化短信的广播
        InnerReceiver receiver = new InnerReceiver();
        IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
        filter.setPriority(Integer.MAX_VALUE);
        registerReceiver(receiver,filter);
    }


    private class MyPhoneStateListener extends PhoneStateListener {
        //电话状态改变监听
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            // @see TelephonyManager#CALL_STATE_IDLE  电话闲置
            // @see TelephonyManager#CALL_STATE_RINGING 电话铃响的状态
            // @see TelephonyManager#CALL_STATE_OFFHOOK 电话接通
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    String mode = dao.findNumber(incomingNumber);
                    /**
                     * 黑名单拦截模式
                     * 3 全部拦截 电话拦截 + 短信拦截
                     * 1 电话拦截
                     * 2 短信拦截
                     */
                    if ("1".equals(mode) || "2".equals(mode)) {
                        Uri uri = Uri.parse("content://call_log/calls");
                        getContentResolver().registerContentObserver(uri,true,new MyContentObserver(new Handler(),incomingNumber));
                        //挂断电话
                        endCall();
                    }
                    break;
            }
        }
    }

    /**
     * 内容观察者
     */
    private class MyContentObserver extends ContentObserver {
        private String phone;
        /**
         * Creates a content observer.
         * @param handler The handler to run {@link #onChange} on, or null if none.
         */
        public MyContentObserver(Handler handler, String phone) {
            super(handler);
            this.phone = phone;
        }

        /**
         * 当数据改变时调用
         */
        @Override
        public void onChange(boolean selfChange) {
            getContentResolver().unregisterContentObserver(this);
            //删除电话号码
            deleteCallLog(phone);
            super.onChange(selfChange);
        }
    }
    //从数据库删除拨打记录
    private void deleteCallLog(String phone){
        Uri uri = Uri.parse("content://call_log/calls");
        getContentResolver().delete(uri,"number=?",new String[]{phone});
    }

    private void endCall () {
        try {
            //通过类加载器加载ServiceManager
            Class<?> clazz = getClassLoader().loadClass("android.os.ServiceManager");
            //通过反射得到当前的方法
            Method method = clazz.getDeclaredMethod("getService", String.class);
            //使用电话拨打器关闭电话
            IBinder iBinder = (IBinder) method.invoke(null, TELEPHONY_SERVICE);
            ITelephony iTelephony = ITelephony.Stub.asInterface(iBinder);//创建中间人
            iTelephony.endCall();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class InnerReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("有短信来了");
            Object[] objects = (Object[]) intent.getExtras().get("pdus");

            for (Object object : objects) {
                // 超出的话,会分为多条短信发送,所以是一个数组,因为我们的短信指令很短,所以for循环只执行一次
                SmsMessage message = SmsMessage.createFromPdu((byte[]) object);
                String address = message.getDisplayOriginatingAddress();
                String body = message.getMessageBody();

                String mode = dao.findNumber(address);
                if("2".equals(mode) || "3".equals(mode)) {
                    abortBroadcast();
                }
                //根据内容拦截
                if (body.contains("我爱你")) {
                    abortBroadcast();
                }

                //根据内容拦截
                if (body.contains("love")) {
                    abortBroadcast();
                }

                //根据手机号拦截
                if ("18825166418".equals(address)) {
                    abortBroadcast();
                }
            }
        }
    }
}
